﻿using Dapper;
using Dapper.Contrib.Extensions;
using EC.Application.Interface;
using EC.Entity;
using EC.Entity.Query;
using EC.Entity.Request.Bank;
using EC.Entity.Response.Bank;
using EC.Entity.Tables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EC.Application.Impl
{
    public class BankServiceImpl : BankService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public BankServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }

        #endregion


        public BankResponse Get(int id)
        {
            var bankListResponse = _dbSession.DbConnection.QueryFirst<BankResponse>("select * from banklist where Id=@Id", new { Id = id });
            if (bankListResponse != null)
            {
                return bankListResponse;
            }
            return null;
        }


        public BankResponse GetBankByCode(string bankCode)
        {
            var bankListResponse = _dbSession.DbConnection.QueryFirst<BankResponse>("select * from banklist where bankCode=@BankCode", new { BankCode = bankCode.ToUpper() });
            if (bankListResponse != null)
            {
                return bankListResponse;
            }
            return null;
        }


        public DataGrid<BankResponse> GetPager(BankQuery query)
        {
            var files = "Id,BankCode,BankName,Remark,CreatedBy,CreatedDate";
            var tableName = "banklist";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1 ";

            //查询条件
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrEmpty(query.BankCode))
            {
                where += " and BankCode  LIKE @BankCode";
                parameters.Add("BankCode", "%" + query.BankCode + "%");
            }

            if (!string.IsNullOrEmpty(query.BankName))
            {
                where += " and BankName LIKE  @BankName";
                parameters.Add("BankName", "%" + query.BankName + "%");
            }



            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, (query.Page.Value - 1) * query.Rows.Value, query.Rows.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString(), parameters))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<BankResponse>();


                return new DataGrid<BankResponse>()
                {
                    Total = count,
                    Rows = list,
                    Success = true
                };
            }
        }

        /// <summary>
        /// 更新或新增
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveBank(SaveBankRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (string.IsNullOrEmpty(request.BankCode) || string.IsNullOrEmpty(request.BankName))
            {
                throw new Exception("银行名称和银行编码都不能为空.");
            }
            request.BankCode=request.BankCode.ToUpper();

            //更新
            if (request.Id > 0)
            {
                var bankList = _dbSession.DbConnection.QueryFirst<BankList>($"select * from banklist where Id=@Id", new { request.Id });
                if (bankList == null)
                {
                    throw new Exception("银行记录不存在.");
                }

                bankList.BankName = request.BankName.Trim();
                bankList.BankCode = request.BankCode.Trim();
                bankList.Remark = request.Remark?.Trim();
                _dbSession.DbConnection.Update(bankList);

                response.Success = true;
            }
            else
            {
                //新增
                var bankCodeExist = _dbSession.DbConnection.Query<BankList>($"SELECT * FROM banklist WHERE BankCode=@BankCode", new { request.BankCode });
                if (bankCodeExist != null && bankCodeExist.Any())
                {
                    throw new Exception("银行编码已存在.");
                }

                var bankNameExist = _dbSession.DbConnection.Query<BankList>($"SELECT * FROM banklist WHERE BankName=@BankName", new { request.BankName });
                if (bankNameExist != null && bankNameExist.Any())
                {
                    throw new Exception("银行名称已存在.");
                }

                var bankList = new BankList()
                {
                    BankName = request.BankName.Trim(),
                    BankCode = request.BankCode.Trim(),
                    Remark = request.Remark.Trim(),
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };

                long resultId = _dbSession.DbConnection.Insert(bankList);

                if (resultId <= 0)
                {
                    throw new Exception("新增银行信息失败.");
                }
                response.Success = true;
            }
            return response;
        }


        public JResult DelBank(int Id)
        {
            var response = new JResult()
            {
                Success = false
            };

            int count = _dbSession.DbConnection.Execute("delete FROM banklist WHERE Id=@Id", new { Id });
            if (count <= 0)
            {
                throw new Exception("删除银行信息失败.");
            }
            response.Success = true;

            return response;
        }

    }
}
